package org.mokusakura.persistence.Util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCodeGenerator {
    private static final int WIDTH = 80;
    private static final int HEIGHT = 20;
    private static final String STRING = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    private static final int LENGTH = STRING.length();
    private static final Random RANDOM = new Random();

    public static String GenerateVerifyCode(BufferedImage bufferedImage) {
        Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.fillRect(0, 0, WIDTH, HEIGHT);


        graphics2D.setFont(new Font("Times New Roman", Font.PLAIN, 26));
        //Random String
        String randString = randomString(4);
        for (int i = 0; i < randString.length(); i++) {
            char rand = randString.charAt(i);
            graphics2D.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255)));
            graphics2D.drawString(String.valueOf(rand), 20 * i + 5, 20);
        }
        //Line to interfere
        graphics2D.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255)));
        graphics2D.drawLine(RANDOM.nextInt(10), RANDOM.nextInt(HEIGHT), RANDOM.nextInt(10) + 70,
                            RANDOM.nextInt(HEIGHT));
        graphics2D.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255)));
        graphics2D.drawLine(RANDOM.nextInt(10), RANDOM.nextInt(HEIGHT), RANDOM.nextInt(10) + 70,
                            RANDOM.nextInt(HEIGHT));
        graphics2D.dispose();
        return randString;
    }

    public static String randomString(int size) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < size; i++) {
            char rand = STRING.charAt(RANDOM.nextInt(LENGTH));
            res.append(rand);
        }
        return res.toString();
    }

}
